'use strict';
/**
 * @fileoverview 玩家激活码
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var _ = require('lodash');
var cdkItemSchema = require('./cdk/cdkItemSchema');

/**
 * 激活码
 */
var cdkSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 激活码类型列表
    cdk_list: [cdkItemSchema]
});

/**
 * 验证激活码
 * @return {[type]} [description]
 */
cdkSchema.methods.verify = function (cdk_type, limit_times) {
    for (var i = 0; i < this.cdk_list.length; i++) {
        var cdk_item = this.cdk_list[i];
        if (cdk_item.cdk_type == cdk_type) {
            if (cdk_item.use_times >= limit_times) {
                return false;
            } else {
                cdk_item.use_times++;
                return true;
            }
        }
    }

    this.cdk_list.push({
        cdk_type: cdk_type,
        use_times: 1
    });
    return true;
};

cdkSchema.methods.push = function () {

};

if (!cdkSchema.options.toJSON) {
    cdkSchema.options.toJSON = {};
}
/* jshint unused:false */
cdkSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

mongoose.model('Cdk', cdkSchema);
